package com.example.a10928.weifriend.ui.home.menu;

import android.content.Intent;
import android.databinding.ObservableChar;
import android.databinding.ObservableField;
import android.databinding.ObservableInt;
import android.databinding.ViewDataBinding;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v7.widget.GridLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;

import com.example.a10928.weifriend.R;
import com.example.a10928.weifriend.adapter.GridImageAdapter;
import com.example.a10928.weifriend.databinding.ActivityWerbenBinding;
import com.example.a10928.weifriend.ui.DatabindingBaseActivity;
import com.example.a10928.weifriend.util.L;
import com.example.a10928.weifriend.manager.FullyGridLayoutManager;
import com.example.a10928.weifriend.util.RxUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;

import static com.example.a10928.weifriend.App.app;

public class WerbenActivity extends DatabindingBaseActivity {

    private ActivityWerbenBinding mBinding;
    private List<LocalMedia> selectList = new ArrayList<>();
    private GridImageAdapter adapter;
    public ObservableInt number = new ObservableInt(0);
    public ObservableField<String> price = new ObservableField("0");

    @Override
    protected void bindingInitData() {
        adapter = new GridImageAdapter(this, addPicClickListener);
        adapter.setOnItemClickListener(listener);
        getPriceAndSize();

    }

    @Override
    protected void bindingInitView(ViewDataBinding viewDataBinding) {
        setTitleText(ThemeEnum.Back_Default, "我要打广告");
        mBinding = (ActivityWerbenBinding) viewDataBinding;
        mBinding.setView(this);
        mBinding.werbenAddRv.setAdapter(adapter);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        mBinding.werbenAddRv.setLayoutManager(manager);
        mBinding.werbenEtTaskSize.addTextChangedListener(textWatcher);
        mBinding.werbenEtSinglePrice.setEnabled(false);
    }


    @Override
    protected int bindingGetContentView() {
        return R.layout.activity_werben;
    }

    public void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.werben_bt_send:
                if (checkView()) {
                    Intent intent = new Intent(this, PaySelectActvitiy.class);
                    WerbenData data = new WerbenData(
                            mBinding.werbenEtTitle.getText().toString(),
                            mBinding.werbenEtInfo.getText().toString(),
                            price.get(),
                            mBinding.werbenEtTaskSize.getText().toString(),
                            selectList

                    );
                    intent.putExtra(PaySelectActvitiy.SOURCE_PAYSELECTACTIVITY_TYPE, PaySelectActvitiy.SOURCE_WERBEN_ACTIVITY);
                    intent.putExtra("werbenData", data);
                    startActivity(intent);
                }
                break;
        }
    }

    private GridImageAdapter.onAddPicClickListener addPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            createPictureSelector();
        }
    };

    private void createPictureSelector() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .maxSelectNum(6)
                .minSelectNum(1)
                .imageSpanCount(4)
                .selectionMedia(selectList)
                .selectionMode(PictureConfig.MULTIPLE)
                .previewImage(true)
                .isCamera(true)
                .isZoomAnim(true)
                .compress(true)
                .previewEggs(true)
                .glideOverride(160, 160)
                .minimumCompressSize(500)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }


    public boolean checkView() {
        if (TextUtils.isEmpty(mBinding.werbenEtTitle.getText().toString().trim())) {
            L.t("标题不能为空");
            return false;
        } if (TextUtils.isEmpty(mBinding.werbenEtInfo.getText().toString().trim())) {
            L.t("内容不能为空");
            return false;
        } if (TextUtils.isEmpty(mBinding.werbenEtTaskSize.getText().toString().trim())) {
            L.t("数量不能为空");
            return false;
        } if (selectList.size() == 0) {
            L.t("图片不能为空");
            return false;
        } if (Integer.parseInt(mBinding.werbenEtTaskSize.getText().toString()) < number.get()) {
            L.t("广告最低发布数量为" + number + "条"); return false;
        }
        if(Integer.parseInt(mBinding.werbenEtTaskSize.getText().toString()) * Double.parseDouble(price.get())>5000){
            L.t("单笔支付最高5000元，如大额支付请分多笔支付或与客服联系"); return false;
        }
        return true;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    for (LocalMedia media : selectList) {
                        Log.i("图片-----》", media.getPath());
                    }
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    void getPriceAndSize() {
        app().getBpService().getAdverType(app().getUser().getUserId())
                .compose(RxUtil.io2mainLoad(this))
                .subscribe(
                        r -> {
                            number.set(r.getData().get(0).getAd_number());
                            price.set(r.getData().get(0).getAd_unit_price());
                        },
                        RxUtil::errorException
                );
    }

    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if(mBinding.werbenEtTaskSize.getText().toString().equals("")){
                return;
            }
            mBinding.werbenTvTotalPrices.setText(Integer.parseInt(mBinding.werbenEtTaskSize.getText().toString()) * Double.parseDouble(price.get()) + " ￥");
        }
    };

    GridImageAdapter.OnItemClickListener listener = new GridImageAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(int position, View v) {
            if (selectList.size() > 0) {
                LocalMedia media = selectList.get(position);
                String pictureType = media.getPictureType();
                int mediaType = PictureMimeType.pictureToVideo(pictureType);
                switch (mediaType) {
                    case 1:
                        // 预览图片 可自定长按保存路径
                        //PictureSelector.create(MainActivity.this).themeStyle(themeId).externalPicturePreview(position, "/custom_file", selectList);
                        PictureSelector.create(WerbenActivity.this).themeStyle(R.style.picture_default_style).openExternalPreview(position, selectList);
                        break;
                    case 2:
                        // 预览视频
                        PictureSelector.create(WerbenActivity.this).externalPictureVideo(media.getPath());
                        break;
                    case 3:
                        // 预览音频
                        PictureSelector.create(WerbenActivity.this).externalPictureAudio(media.getPath());
                        break;
                }
            }
        }
    };

    public static class WerbenData implements Parcelable {
        public String title;
        public String content;
        public String price;
        public String number;
        public List<LocalMedia> imgList;

        public WerbenData(String title, String content, String price, String number, List<LocalMedia> imgList) {
            this.title = title;
            this.content = content;
            this.price = price;
            this.number = number;
            this.imgList = imgList;
        }

        @Override
        public int describeContents() { return 0; }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeString(this.title);
            dest.writeString(this.content);
            dest.writeString(this.price);
            dest.writeString(this.number);
            dest.writeTypedList(this.imgList);
        }


        protected WerbenData(Parcel in) {
            this.title = in.readString();
            this.content = in.readString();
            this.price = in.readString();
            this.number = in.readString();
            this.imgList = in.createTypedArrayList(LocalMedia.CREATOR);
        }

        public static final Creator<WerbenData> CREATOR = new Creator<WerbenData>() {
            @Override
            public WerbenData createFromParcel(Parcel source) {return new WerbenData(source);}

            @Override
            public WerbenData[] newArray(int size) {return new WerbenData[size];}
        };
    }


}
